import React, { useEffect, useState } from 'react';
import { Alert, Col, message, Progress, Space, Table, Button, Tag } from 'antd';
import ProTable, { ProColumns, TableDropdown, ActionType } from '@ant-design/pro-table';
import { Column, Line } from '@ant-design/charts';
import ClassCascader from '@/components/classCascader'
import { request } from '../.umi/plugin-request/request';
import StudentsCompletionTable from '../components/studentsCompletionTable';
import * as Qs from 'javascript-stringify';
import { stringify } from 'qs';

export default function({ url }) {
  const [data, setData] = useState(6);
  const [completionData, setCompletionData] = useState(null);
  const [classLeaderboard, setClassLeaderboard] = useState([]);
  const [lastUpdateTime, setLastUpdateTime] = useState(null);
  const [lessonName, setLessonName] = useState(null);
  const [announcement, setAnnouncement] = useState(null);
  const [chartData, setChartData] = useState(null);
  const [totalData, setTotalData] = useState(null);

  var chartConfig = {
    data: [],
    isGroup: true,
    xField: 'college',
    yField: 'rate',
    seriesField: 'grade',
    marginRatio: 0,
    slider: {
      start: 0,
      end: 1,
    },
    label: {
      layout: [{ type: 'interval-adjust-position' }, { type: 'adjust-color' }],
    },
  }

  const queryClass = (className) => {
    const hide = message.loading('请求加载中...', 0);
    request('https://dxx.jsutstudy.work/api/class', {
      method: 'get',
      params: {
        class: className
      }
    })
      .then(function(response) {
        hide();
        if (response){
          setCompletionData(response.data);
        }
      })
  }

  const getClassCascaderData = (data) => {
    if (data.length === 3)
    {
      queryClass(data[data.length - 1]);
    }
  }

  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      search: false,
      sorter: (a, b) => a.rank - b.rank,
    },
    {
      title: '学院',
      dataIndex: 'college',
      key: 'college',
      search: false,
      filters: true,
      valueEnum: {
        "计算机工程学院": {
          text: '计算机工程学院',
        },
        "文化与旅游学院": {
          text: '文化与旅游学院',
        },
        "化学与环境工程学院": {
          text: '化学与环境工程学院',
        },
        "国际教育学院": {
          text: '国际教育学院',
        },
        "外国语学院": {
          text: '外国语学院',
        },
        "教育学院": {
          text: '教育学院',
        },
        "数理学院": {
          text: '数理学院',
        },
        "机械工程学院": {
          text: '机械工程学院',
        },
        "材料工程学院": {
          text: '材料工程学院',
        },
        "汽车与交通工程学院": {
          text: '汽车与交通工程学院',
        },
        "电气信息工程学院": {
          text: '电气信息工程学院',
        },
        "艺术设计学院": {
          text: '艺术设计学院1',
        },
        "管理学院":{
          text: '管理学院',
        },
        "经济学院":{
          text: '经济学院',
        }
      },
    },
    {
      title: '班级',
      dataIndex: 'name',
      key: 'name',
      filters: true,
      render: (className) => (<a onClick={() => queryClass(className)}>{className}</a>)
    },
    {
      title: '完成人数',
      dataIndex: 'finish',
      key: 'finish',
      search: false,
      sorter: (a, b) => a.finish - b.finish,
    },
    {
      title: '总人数',
      dataIndex: 'total',
      key: 'total',
      search: false,
      sorter: (a, b) => a.finish - b.finish,
    },
    {
      title: '完成率',
      dataIndex: 'rate',
      key: 'rate',
      search: false,
      sorter: (a, b) => a.rate - b.rate,
      render: (value) => {
        let color = value >= 100 ? 'success' : 'active';
        return (
          <Progress percent={parseFloat(value).toFixed(2)} status={color}/>
        )
      },
    }
  ];


  return (
    <Space direction="vertical" style={{ width: "100%"}}>
      <Col span={24} key = '5' >
        <span>班级完成情况详情: </span>
        <ClassCascader url={"https://dxx.jsutstudy.work/api/getCascadeSelect"} onChange={getClassCascaderData} />
        {completionData &&
          <Button  type="primary" style={{float: "right"}} onClick={() => setCompletionData(null)}>返回</Button>
        }
      </Col>
      { announcement &&
      <Alert message={announcement} type="warning" showIcon />
      }
      { lastUpdateTime && lessonName &&
      <Alert message={"数据统计截至：" + lastUpdateTime + " | " + lessonName} type="info" showIcon />
      }
      {totalData && !completionData &&
        <>
          <Progress status={'active'} percent={parseFloat(totalData.finish/totalData.total*100).toFixed(2)} format={(value) => value + "%"} />
        </>
      }
      {chartData && !completionData &&
        <Column {...chartData} />
      }
      {classLeaderboard && !completionData &&
        <ProTable
          columns={columns}
          options={{
            search: true,
          }}
          request={async (params = {}, sort, filter = null) => {
            // FIXED 手动拼接由于params中存在数组时无法筛选的情况
            return request('https://dxx.jsutstudy.work/api/getStatistics?' + stringify(params) + (filter && ("&" + stringify(filter, { arrayFormat: 'brackets' }))));
          }}
          toolBarRender={() => [
            <Button key="out" type={'primary'} onClick={() => window.open("https://dxx.jsutstudy.work/api/getStatistics?download=1")}>
              导出数据
            </Button>,
          ]}
          postData={(data) => {
            setLastUpdateTime(data.update_time);
            setLessonName(data.lesson_name);
            setAnnouncement(data.announment);
            chartConfig.data = data.college;
            setChartData(chartConfig);
            setTotalData(data.total);



            return data.class;
          }}
          rowKey="name"
          pagination={{
            showQuickJumper: true,
          }}
          search={false}
          dateFormatter="string"
          headerTitle="全校各班完成情况 "
        />
      }
      {completionData &&
        <>
          {/*<Alert message={"数据统计截至：" + completionData.update_time + " | " + completionData.lesson_name} type="info" showIcon />*/}
          <Alert message={"完成情况未知主要是因为学院内有重名情况，一般情况下无法统计是否完成。"} type="error" showIcon />
          <Progress percent={parseFloat(completionData.finish/completionData.total).toFixed(2)*100} format={() => completionData.finish + "/" + completionData.total} />
          <StudentsCompletionTable data={completionData.resource} />
        </>
      }
    </Space>
  );
}
